﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using log4net;
using McsUtility;

namespace MinerManager.Forms
{
	public partial class MinerBatchConfiguration : DevExpress.XtraEditors.XtraForm
	{
		ILog logger = LogManager.GetLogger(typeof(Program));
		private Common.AgentComponent Agent = null;
		private List<Models.MinerModel> Miners = new List<Models.MinerModel>();

		public event EventHandler<ObjectEventArgs> OnSuccess;

		public MinerBatchConfiguration(Common.AgentComponent agent, List<Models.MinerModel> miners)
		{
			InitializeComponent();
			this.Agent = agent;
			this.Miners = miners;
		}

		#region 窗体事件

		private void MinerBatchConfiguration_Load(object sender, EventArgs e)
		{
			ItemEditMinerName.Checked = false;
			ItemAutoUpdate.Checked = true;
			ItemMinerNameNumber.Text = "1";
			ItemEditMinerName_CheckedChanged(ItemEditMinerName, new EventArgs());

			//最高温度
			List<ComboboxListItem> itemsMaxTemp = new List<ComboboxListItem>()
			{
				new ComboboxListItem("70", "70"),
				new ComboboxListItem("75", "75"),
				new ComboboxListItem("80", "80"),
				new ComboboxListItem("85", "85"),
				new ComboboxListItem("90", "90")
			};
			Utility.Forms.SetComboBoxEdit(this, "ItemMaxTemp", itemsMaxTemp);

			//最低转速
			List<ComboboxListItem> itemsMinFan = new List<ComboboxListItem>();
			itemsMinFan.Add(new ComboboxListItem ( "驱动智能控制",  "0" ));
			for (int i = 40; i <= 100; i += 5)
			{
				itemsMinFan.Add(new ComboboxListItem(i.ToString(), i.ToString()));
			}
			Utility.Forms.SetComboBoxEdit(this, "ItemMinFan", itemsMinFan);

			//总算力预警值
			List<ComboboxListItem> itemsMinSpeed = new List<ComboboxListItem>();
			for (int i = 5; i <= 500; i += 5)
			{
				itemsMinSpeed.Add(new ComboboxListItem(i.ToString(), i.ToString()));
			}
			Utility.Forms.SetComboBoxEdit(this, "ItemMinSpeed", itemsMinSpeed);

			//主币币种
			List<ComboboxListItem> itemsFirstCurrency = new List<ComboboxListItem>();
			foreach (McsUtility.Models.CurrencysModel info in Common.Data.UserCurrency.Where(p => p.Type == 1))
			{
				itemsFirstCurrency.Add(new ComboboxListItem(info.Remark, info.Name));
			}
			Utility.Forms.SetComboBoxEdit(this, "FirstCurrency", itemsFirstCurrency);

			//辅币币种
			List<ComboboxListItem> itemsSecondCurrency = new List<ComboboxListItem>();
			foreach (McsUtility.Models.CurrencysModel info in Common.Data.UserCurrency.Where(p => p.Type == 2))
			{
				itemsSecondCurrency.Add(new ComboboxListItem(info.Remark, info.Name));
			}
			Utility.Forms.SetComboBoxEdit(this, "SecondCurrency", itemsSecondCurrency);

			//算力比重
			List<ComboboxListItem> itemsDcri = new List<ComboboxListItem>();
			for (int i = 0; i <= 50; i += 5)
			{
				int num = i > 0 ? i : 1;
				itemsDcri.Add(new ComboboxListItem(num.ToString(), num.ToString()));
			}
			Utility.Forms.SetComboBoxEdit(this, "SecondDcri", itemsDcri, "20");
		}

		private void MinerBatchConfiguration_FormClosing(object sender, FormClosingEventArgs e)
		{
		}

		#endregion

		#region void ItemEditMinerName_CheckedChanged(object sender, EventArgs e)

		private void ItemEditMinerName_CheckedChanged(object sender, EventArgs e)
		{
			if (ItemEditMinerName.Checked)
			{
				ItemMinerNameBefor.Enabled = true;
				ItemMinerNameNumber.Enabled = true;
				ItemMinerNameEndNumber.Enabled = true;
			}
			else
			{
				ItemMinerNameBefor.Enabled = false;
				ItemMinerNameNumber.Enabled = false;
				ItemMinerNameEndNumber.Enabled = false;
			}
		}

		#endregion

		#region void ItemMinerName_KeyUp(object sender, KeyEventArgs e)

		private void ItemMinerName_KeyUp(object sender, KeyEventArgs e)
		{
			//非法信息检测
			if (!System.Text.RegularExpressions.Regex.IsMatch(ItemMinerNameNumber.Text.Trim(), "^[0-9]+$"))
			{
				if (MessageBox.Show("矿机名起始数只允许输入0到9的数字，开头可以为0。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error) == DialogResult.OK)
				{
					ItemMinerNameNumber.Text = "1";
					ItemMinerNameNumber.SelectAll();
				}
			}

			//起始数
			int number = 1;
			int.TryParse(ItemMinerNameNumber.Text, out number);

			//数字位数
			string lengthFormat = string.Empty;
			int length = ItemMinerNameNumber.Text.Trim().Length;
			for (int i = 0; i < length; i++)
			{
				lengthFormat += "0";
			}

			//矿机名预览
			ItemMinerNameEndNumber.Text = (number + this.Miners.Count - 1).ToString();
			LabelMinerName.Text = ItemMinerNameBefor.Text + number.ToString(lengthFormat);

			if (this.Miners.Count > 1)
			{
				LabelMinerName.Text += " 至 " + ItemMinerNameBefor.Text + (number + this.Miners.Count - 1).ToString(lengthFormat);
			}
		}

		#endregion

		#region void FirstCurrency_SelectedIndexChanged(object sender, EventArgs e)

		private void FirstCurrency_SelectedIndexChanged(object sender, EventArgs e)
		{
			ComboboxListItem item = FirstCurrency.SelectedItem as ComboboxListItem;
			if (item != null)
			{
				McsUtility.Models.CurrencysModel info = Common.Data.UserCurrency.Where(p => p.Name.Equals(item.Value, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();
				if (info != null)
				{
					//钱包信息
					List<ComboboxListItem> itemsWallet = new List<ComboboxListItem>();

					//矿池信息
					List<ComboboxListItem> itemsPool = new List<ComboboxListItem>();

					foreach (McsUtility.Models.WalletsModel infoWallet in info.Wallets)
					{
						itemsWallet.Add(new ComboboxListItem(infoWallet.Address, infoWallet.Address));
					}

					foreach (McsUtility.Models.WalletsModel infoPool in info.OrePools)
					{
						string poolName = (!string.IsNullOrWhiteSpace(infoPool.Remark) ? infoPool.Remark + " " : "") + infoPool.Address;
						itemsPool.Add(new ComboboxListItem(poolName, infoPool.Address));
					}

					Utility.Forms.SetComboBoxEdit(this, "FirstPool", itemsPool);
					Utility.Forms.SetComboBoxEdit(this, "FirstBackupPool", Utility.Clone(itemsPool));
					Utility.Forms.SetComboBoxEdit(this, "FirstWallet", itemsWallet);
				}
			}
		}

		#endregion

		#region void SecondCurrency_SelectedIndexChanged(object sender, EventArgs e)

		private void SecondCurrency_SelectedIndexChanged(object sender, EventArgs e)
		{
			ComboboxListItem item = SecondCurrency.SelectedItem as ComboboxListItem;
			if (item != null)
			{
				McsUtility.Models.CurrencysModel info = Common.Data.UserCurrency.Where(p => p.Name.Equals(item.Value, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();
				if (info != null)
				{
					//钱包信息
					List<ComboboxListItem> itemsWallet = new List<ComboboxListItem>();

					//矿池信息
					List<ComboboxListItem> itemsPool = new List<ComboboxListItem>();

					foreach (McsUtility.Models.WalletsModel infoWallet in info.Wallets)
					{
						itemsWallet.Add(new ComboboxListItem(infoWallet.Address, infoWallet.Address));
					}

					foreach (McsUtility.Models.WalletsModel infoPool in info.OrePools)
					{
						string poolName = (!string.IsNullOrWhiteSpace(infoPool.Remark) ? infoPool.Remark + " " : "") + infoPool.Address;
						itemsPool.Add(new ComboboxListItem(poolName, infoPool.Address));
					}

					Utility.Forms.SetComboBoxEdit(this, "SecondPool", Utility.Clone(itemsPool));
					Utility.Forms.SetComboBoxEdit(this, "SecondWallet", Utility.Clone(itemsWallet));
				}
			}
		}

		#endregion

		#region void BtnSave_Click(object sender, EventArgs e)

		private void BtnSave_Click(object sender, EventArgs e)
		{
			int minerNameNumber = 1;
			decimal minSpeed = 0;
			decimal.TryParse(ItemMinSpeed.Text, out minSpeed);

			#region 非法信息检测

			if (string.IsNullOrWhiteSpace(ItemMinerNameNumber.Text) || (!int.TryParse(ItemMinerNameNumber.Text, out minerNameNumber) && minerNameNumber < 0))
			{
				if (MessageBox.Show("请填写正确的矿机名起始数。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error) == DialogResult.OK)
				{
					ItemMinerNameNumber.Focus();
					ItemMinerNameNumber.SelectAll();
				}
				return;
			}

			if (ItemLowStrengthWarn.Checked && minSpeed < 0)
			{
				if (MessageBox.Show("请填写正确的算力预警值。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error) == DialogResult.OK)
				{
					ItemMinSpeed.Focus();
					ItemMinSpeed.SelectAll();
				}
				return;
			}

			if (FirstCurrency.SelectedItem == null || string.IsNullOrWhiteSpace(((ComboboxListItem)FirstCurrency.SelectedItem).Value))
			{
				if (MessageBox.Show("请选择主币币种。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error) == DialogResult.OK)
				{
					FirstCurrency.Focus();
					FirstCurrency.SelectAll();
				}
				return;
			}

			if (FirstPool.SelectedItem == null || string.IsNullOrWhiteSpace(((ComboboxListItem)FirstPool.SelectedItem).Value))
			{
				if (MessageBox.Show("请选择主币矿池。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error) == DialogResult.OK)
				{
					FirstPool.Focus();
					FirstPool.SelectAll();
				}
				return;
			}

			if (FirstWallet.SelectedItem == null || string.IsNullOrWhiteSpace(((ComboboxListItem)FirstWallet.SelectedItem).Value))
			{
				if (MessageBox.Show("请选择主币钱包。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error) == DialogResult.OK)
				{
					FirstWallet.Focus();
					FirstWallet.SelectAll();
				}
				return;
			}

			if (SecondEnable.Checked)
			{
				if (SecondCurrency.SelectedItem == null || string.IsNullOrWhiteSpace(((ComboboxListItem)SecondCurrency.SelectedItem).Value))
				{
					if (MessageBox.Show("请选择辅币币种。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error) == DialogResult.OK)
					{
						SecondCurrency.Focus();
						SecondCurrency.SelectAll();
					}
					return;
				}

				if (SecondPool.SelectedItem == null || string.IsNullOrWhiteSpace(((ComboboxListItem)SecondPool.SelectedItem).Value))
				{
					if (MessageBox.Show("请选择辅币矿池。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error) == DialogResult.OK)
					{
						SecondPool.Focus();
						SecondPool.SelectAll();
					}
					return;
				}

				if (SecondWallet.SelectedItem == null || string.IsNullOrWhiteSpace(((ComboboxListItem)SecondWallet.SelectedItem).Value))
				{
					if (MessageBox.Show("请选择辅币钱包。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error) == DialogResult.OK)
					{
						SecondWallet.Focus();
						SecondWallet.SelectAll();
					}
					return;
				}
			}

			#endregion

			//内核
			McsUtility.Models.CoreType coreType = (McsUtility.Models.CoreType)Enum.Parse(typeof(McsUtility.Models.CoreType), ItemCoreType.EditValue.ToString());

			//发送数据
			if (this.Agent.IsStarted)
			{
				//数字位数
				string lengthFormat = string.Empty;
				int length = ItemMinerNameNumber.Text.Trim().Length;
				for (int i = 0; i < length; i++)
				{
					lengthFormat += "0";
				}

				for (int i = 0; i < this.Miners.Count; i++)
				{
					string minerName = ItemEditMinerName.Checked ? ItemMinerNameBefor.Text + (minerNameNumber + i).ToString(lengthFormat) : this.Miners[i].MinerName;

					this.Miners[i].AutoUpdate = ItemAutoUpdate.Checked;
					this.Miners[i].MinerName = minerName;
					this.Miners[i].MinFan = ((ComboboxListItem)ItemMinFan.SelectedItem).Value;
					this.Miners[i].MaxFan = "100";
					this.Miners[i].MinTemp = "";
					this.Miners[i].MaxTemp = ((ComboboxListItem)ItemMaxTemp.SelectedItem).Value;
					this.Miners[i].HighTempStrategy = (McsUtility.Models.HighTempStrategy)Enum.Parse(typeof(McsUtility.Models.HighTempStrategy), ItemHighTempStrategy.EditValue.ToString());
					this.Miners[i].HighTempWarn = ItemHighTempWarn.Checked;
					this.Miners[i].LowStrengthWarn = ItemLowStrengthWarn.Checked;
					this.Miners[i].MinSpeed = minSpeed.ToString();
					this.Miners[i].CoreType = coreType;
					this.Miners[i].FirstCoin = ((ComboboxListItem)FirstCurrency.SelectedItem).Value;
					this.Miners[i].FirstPool = ((ComboboxListItem)FirstPool.SelectedItem).Value;
					this.Miners[i].BackupPool = ((ComboboxListItem)FirstBackupPool.SelectedItem).Value;
					this.Miners[i].FirstWallet = ((ComboboxListItem)FirstWallet.SelectedItem).Value;
					this.Miners[i].Second = SecondEnable.Checked;
					this.Miners[i].Dcri = ((ComboboxListItem)SecondDcri.SelectedItem).Value;
					this.Miners[i].SecondCoin = SecondCurrency.SelectedItem != null ? ((ComboboxListItem)SecondCurrency.SelectedItem).Value : "";
					this.Miners[i].SecondPool = SecondEnable.Checked ? ((ComboboxListItem)SecondPool.SelectedItem).Value : "";
					this.Miners[i].SecondWallet = SecondEnable.Checked ? ((ComboboxListItem)SecondWallet.SelectedItem).Value : "";
					this.Miners[i].AdvParams = ItemAdvParams.Text;
					this.Miners[i].Eres = "";

					McsUtility.Models.MinersMiningRequestModel info = new McsUtility.Models.MinersMiningRequestModel
					{
						MinersIDs = new List<int> { this.Miners[i].ID },
						AutoName = false,
						AutoRun = false,
						AutoUpdate = this.Miners[i].AutoUpdate,
						MinerName = this.Miners[i].MinerName,
						MinFan = this.Miners[i].MinFan,
						MaxFan = this.Miners[i].MaxFan,
						MinTemp = this.Miners[i].MinTemp,
						MaxTemp = this.Miners[i].MaxTemp,
						HighTempStrategy = this.Miners[i].HighTempStrategy,
						HighTempWarn = this.Miners[i].HighTempWarn,
						LowStrengthWarn = this.Miners[i].LowStrengthWarn,
						MinSpeed = this.Miners[i].MinSpeed,
						CoreType = this.Miners[i].CoreType,
						FirstCoin = this.Miners[i].FirstCoin,
						FirstPool = this.Miners[i].FirstPool,
						BackupPool = this.Miners[i].BackupPool,
						FirstWallet = this.Miners[i].FirstWallet,
						Second = this.Miners[i].Second,
						Dcri = this.Miners[i].Dcri,
						SecondCoin = this.Miners[i].SecondCoin,
						SecondPool = this.Miners[i].SecondPool,
						SecondWallet = this.Miners[i].SecondWallet,
						AdvParams = this.Miners[i].AdvParams,
						Eres = this.Miners[i].Eres
					};

					byte[] bytes = ProtocolHelper.WritePackage<McsUtility.Models.MinersMiningRequestModel>(ProtoType.MinerManagerModifyOrePoolUrl, info);
					this.Agent.AgentSend(bytes);
				}

				OnSuccess?.Invoke(this, new ObjectEventArgs(this.Miners));
			}
			else
			{
				MessageBox.Show("与服务器的链接断开，请重新登录系统。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
			}
		}

		#endregion

		#region void BtnClose_Click(object sender, EventArgs e)

		private void BtnClose_Click(object sender, EventArgs e)
		{
			this.Close();
		}

		#endregion
	}
}